extends StaticBody2D

var item_map = {
	"fire_flower": Rect2(0,32,16,16),
	"1_up_mushroom": Rect2(16,0,16,16),
	"super_stars": Rect2(0,48,16,16)
	}
var box_show_map = {
	"brick": Rect2(16,0,16,16),
	"closeBox": Rect2(384,0,16,16),
	"openBox": Rect2(432,0,16,16)
}

@onready var sprite_default: Sprite2D = $SpriteDefault
@onready var sprite_item: Sprite2D = $SpriteItem
@onready var animation_player: AnimationPlayer = $AnimationPlayer
@onready var obj_coin = $ObjCoin
const COIN = preload("res://asserts/sound/coin.ogg")
const POWERUP_APPEARS = preload("res://asserts/sound/powerup_appears.ogg")

var item_picked := false

@export_enum("fire_flower","1_up_mushroom","super_stars","coins") var prop_item_name : String = "fire_flower" ## 道具的类型
@export var prop_item_count : int = 1 ## 道具的初始数量
@export_enum("hidden","close","open") var prop_box_status : String = "close" ## box的初始状态


@export_enum("transparent","brick","closeBox","openBox") var prop_box_hidden_show : String  = "transparent" ## box处于hiden时，盒子的展现样式
@export_enum("brick","closeBox","openBox") var prop_box_close_show : String  = "closeBox" ## box处于close时，盒子的展现样式
@export_enum("brick","openBox") var prop_box_open_show : String  = "openBox" ## box处于open时，盒子的展现样式


func set_box_transparent():
	sprite_default.visible = false
	sprite_item.visible = false
	obj_coin.visible = false

# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	match prop_box_status:
		"hidden":
			if prop_box_hidden_show == "transparent":
				set_box_transparent()
			else:
				sprite_default.region_rect = box_show_map[prop_box_hidden_show]
		"close":
			sprite_default.region_rect = box_show_map[prop_box_close_show]
		"open":
			sprite_default.region_rect = box_show_map[prop_box_open_show]

func _on_item_box_body_entered(body: Node2D) -> void:
	if prop_box_status == "hidden":
		prop_box_status = "close"
		sprite_default.region_rect = box_show_map[prop_box_close_show]
		sprite_default.visible = true
		sprite_item.visible = true
		return
	if prop_box_status == "close":
		# play animation
		if prop_item_name == "coins":
			obj_coin.visible = true
			obj_coin.get_node("AnimationPlayer").play("collect")
			$AudioStreamPlayer.stream = COIN
			$AudioStreamPlayer.play()
		else:
			sprite_item.region_rect = item_map[prop_item_name]
			animation_player.play("rise", -1,2.5)
		prop_item_count = max(0,prop_item_count-1)
		
		if prop_item_count == 0:
			prop_box_status = "open"
			sprite_default.region_rect = box_show_map[prop_box_open_show]
		return



func _on_sprite_item_body_entered(body: Node2D) -> void:
	if item_picked:
		return
	print("player pick up item %s !" % prop_item_name )
	get_node("Items/%s" % prop_item_name).pick_up(body,$AudioStreamPlayer)
	sprite_item.visible = false
	item_picked = true
	
